<?php
/**
 * @author Anh Nguyen
 * @copyright 2012
 */
 defined('APP') or die('Denied access !');
 
 class Router
 {
    public static $module = '';
    public static $controller = '';
    public static $action = '';
    public static $param = '';
    private static $module_default;
    
    public static function init()
    {
        self::$module_default = Core::$config['module_default'];
        self::_fetch_uri();
        $classname = ucfirst(self::$module) . '_Controller_' . ucfirst(self::$controller);
        $controller = new $classname();
        if( !is_callable(array($controller, self::$action . 'Action'))) {
            $action = 'indexAction';
        } else {
            $action = self::$action . 'Action';
        }
        $controller->$action(self::$param);
    }
    
    private static function _fetch_uri()
    {
        $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
        $module = $control = $action = $param = '';
        $full_uri = FALSE;
        if(preg_match('#^/?(?P<module>[\w]+)?(?:/(?P<control>[\w]+))?(?:/(?P<action>[\w]+))?(?:/(?P<param>[\d]+))?#', $uri, $matches)) {
            extract($matches);
        }
        foreach(Core::$module as $modules)
        {
            if($modules == $module) {
                $full_uri = TRUE;
                break;
            }
        }
        
        if($full_uri == TRUE) {
            self::$module = $module;
            self::$controller = (empty($control)) ? 'index' : $control;
            self::$action = (empty($action)) ? 'index' : $action;
            self::$param = $param;
        } else {
            self::$module = self::$module_default;
            self::$controller = (empty($module)) ? 'index' : $module;
            self::$action = (empty($control)) ? 'index' : $control;
            self::$param = $action;
        }
    }
 }
?>